import { App } from "vue";
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import { createRouterGuards } from "./router-guards";
import { h, Component } from 'vue'
import { NIcon } from "naive-ui";
const modules: Record<
  string,
  Record<string, RouteRecordRaw[]>
> = import.meta.globEager("./modules/*.ts");

const routeModuleList: RouteRecordRaw[] = [];

// 拼接需要权限
Object.keys(modules).forEach((key: string) => {
  const mod = modules[key].default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  routeModuleList.push(...modList);
});

const sortRoute = (a, b) => {
  return (a?.meta.sort || 0) - (b?.meta.sort || 0)
}

routeModuleList.sort(sortRoute)



// 登录路由
export const LoginRoute: RouteRecordRaw = {
  path: "/login",
  name: "login",
  component: () => import("@/views/login/index.vue"),
  meta: {
    title: "登录",
  },
}
// 根路由
export const RootRoute: RouteRecordRaw = {
  path: "/",
  name: "root",
  component: () => import("@/views/login/index.vue"),
  meta: {
    title: "登录",
  },
}


//需要验证权限
export const asyncRoutes = [...routeModuleList];

//普通路由 无需验证权限
export const constantRouter: RouteRecordRaw[] = [LoginRoute, RootRoute];



/**
 * 判断是否为根路由
 * @param item 当前路由
 */
export const isRootRouter = (item) => {
  return item.meta?.isRoot && item?.children?.length === 1;
}

export function renderIcon(icon: string) {
  return () => h('img', { src: icon, width: 24, height: 24 }, { default: () => null })
}


const router = createRouter({
  routes: constantRouter,
  history: createWebHistory(),
});


export function setupRouter(app: App) {
  app.use(router)
  // 创建路由守卫
  createRouterGuards(router)
}

export default router;
